<template>
	<div class="layout-padding">
		<splitpanes horizontal>
			<pane size="50">
				<div class="layout-padding-auto layout-padding-view">
					<el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
						<el-form-item :label="$t('pickApply.applyCode')" prop="PickApplyCode">
							<el-input v-model="state.queryForm.PickApplyCode" clearable :placeholder="$t('pickApply.applyCode')"/>
						</el-form-item>
						<el-form-item :label="$t('pickApply.createDate')" prop="createDate">
							<div class="block">
								<el-date-picker v-model="createDate" clearable type="daterange" unlink-panels range-separator="To"
									start-placeholder="Start date" end-placeholder="End date" :shortcuts="shortcuts" />
							</div>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" icon="search"  @click="query"> {{ $t('so.query')
								}}</el-button>
							<el-button type="info" icon="refresh" plain @click="resetQuery">{{ $t('so.reset') }}</el-button>
							<el-button type="success" @click="audit">{{ $t('pickApply.audit')
								}}</el-button>
							<el-button  type="success" @click="notAudit">{{ $t('pickApply.notAudit')
								}}</el-button>
									<el-button  type="danger" icon="delete"  @click="deletePickApply">{{ $t('pickApply.delete')
								}}</el-button>
									<el-button type="warning" effect="dark"  @click="closed">{{ $t('pickApply.closed')
								}}</el-button>
								<el-button type="success" icon="Download" plain  @click="exportPickApply">{{ $t('pickApply.export')
								}}</el-button>
								<el-button type="success" icon="Download" plain @click="exportNotFinish">{{ $t('pickApply.exportNotFinish')
								}}</el-button>
								<el-button  type="primary" icon="plus"  @click="onOpenAddMenu">{{ $t('pickApply.add')
								}}</el-button>
						</el-form-item>
					</el-form>
					<el-table :data="state.dataList" highlight-current-row v-loading="state.loading" border
						style="width: 100%; height: 100%" :cell-style="tableStyle.cellStyle" stripe ref="tableRef"
						:header-cell-style="tableStyle.headerCellStyle" @row-click="clickRow">
						<el-table-column type="selection" width="40" align="center" />
						<el-table-column type="index" label="#" width="60" />
						<el-table-column prop="apply_code" :label="$t('pickApply.applyCode')" show-overflow-tooltip width="150" />
						<el-table-column prop="material_code" :label="$t('pickApply.materialCode')" show-overflow-tooltip width="100" />
						<el-table-column prop="design_color" :label="$t('pickApply.designColor')" show-overflow-tooltip width="150"/>
						<el-table-column prop="status" :label="$t('pickApply.status')" show-overflow-tooltip width="100">
							<template #default="scope">
								<el-tag :type="getTagType(scope.row.status)" effect="dark">
								{{ scope.row.realStatus }}
								</el-tag>
							</template>
						</el-table-column>
						<el-table-column prop="audit_status" :label="$t('pickApply.auditStatus')" show-overflow-tooltip width="100">
							<template #default="scope">
								<el-tag  :type="scope.row.audit_status === 'audited' ? 'success' : (scope.row.audit_status === 'notAudit' ? 'warning' : 'danger')" effect="dark">
								{{ scope.row.realAuditStatus }}
								</el-tag>
							</template>
						</el-table-column>
						<el-table-column prop="planDateStartFormat" :label="$t('pickApply.planDateStart')" width="120"
							show-overflow-tooltip />
						<el-table-column prop="planDateEndFormat" :label="$t('pickApply.planDateEnd')" width="120"
							show-overflow-tooltip />
						<el-table-column prop="plan_days" :label="$t('pickApply.planDays')"
							show-overflow-tooltip width="100"/>
						<el-table-column prop="creationTime" :label="$t('pickApply.creationTime')"  width="150"
							show-overflow-tooltip />
							<el-table-column prop="createUserName" :label="$t('pickApply.createUserName')"
							show-overflow-tooltip width="100"/>
							<el-table-column prop="trunks" :label="$t('pickApply.trunks')"
							show-overflow-tooltip width="100">
                <template #default="scope" >
                  <el-tag :type="+scope.row.trunks > 0 ? 'primary' : 'info'" size="small" effect="plain">
                    {{ scope.row.trunks }}
                  </el-tag>
                </template>
            </el-table-column>>
							<el-table-column prop="material_numbers" :label="$t('pickApply.materialNumbers')"
							show-overflow-tooltip width="100">
                <template #default="scope" >
                  <el-tag :type="+scope.row.material_numbers > 0 ? 'primary' : 'info'" size="small" effect="plain">
                    {{ scope.row.material_numbers }}
                  </el-tag>
                </template>
              </el-table-column>>
							<el-table-column prop="barcode_numbers" :label="$t('pickApply.barcodeNumbers')"
							show-overflow-tooltip width="100">
                <template #default="scope" >
                  <el-tag :type="+scope.row.barcode_numbers > 0 ? 'primary' : 'info'" size="small" effect="plain">
                    {{ scope.row.barcode_numbers}}
                  </el-tag>
                </template>
                </el-table-column>>
							<el-table-column prop="material_qty" :label="$t('pickApply.materialQty')"  width="120" show-overflow-tooltip>
                <template #default="scope">
                  <el-tag :type="+scope.row.material_qty > 0 ? 'success' : 'info'" size="small" effect="dark">
                    {{ scope.row.material_qty }}
                  </el-tag>
                </template>
            </el-table-column>>
							<el-table-column prop="out_barcode_numbers" :label="$t('pickApply.outBarcodeNumbers')"  width="120" show-overflow-tooltip>
                <template #default="scope" >
                  <el-tag :type="+scope.row.out_barcode_numbers > 0 ? 'success' : 'danger'" size="small" effect="plain">
                    {{ scope.row.out_barcode_numbers }}
                  </el-tag>
                </template>
            </el-table-column>>
							<el-table-column prop="out_material_qty" :label="$t('pickApply.outMaterialQty')"  width="120"
							show-overflow-tooltip >
                <template #default="scope">
            <el-tag :type="+scope.row.out_material_qty > 0 ? 'warning' : 'danger'" size="small" effect="plain">
              {{ scope.row.out_material_qty }}
            </el-tag>
                </template>
            </el-table-column>>
							<el-table-column prop="waitoutBarcodeNumbers" :label="$t('pickApply.WaitoutBarcodeNumbers')"  width="120"
							show-overflow-tooltip >
                <template #default="scope">
            <el-tag type="success"  size="small" effect="plain">
              {{ scope.row.waitoutBarcodeNumbers }}
            </el-tag>
                </template>
            </el-table-column>>
							<el-table-column prop="waitOutMaterialQty" :label="$t('pickApply.WaitOutMaterialQty')" width="120"
							show-overflow-tooltip >
                <template #default="scope">
                <el-tag type="warning" size="small" effect="dark">
                  {{ scope.row.waitOutMaterialQty }}
                </el-tag>
                </template>
              </el-table-column>>
					</el-table>
					<pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle"
						v-bind="state.pagination" />
				</div>
				<MenuDialog @refresh="getDataList" ref="menuDialogRef"/>
			</pane>
			<pane size="50">
				<splitpanes>
           <detail ref="detailsRef"/>
				</splitpanes>
			</pane>
		</splitpanes>

	</div>

</template>


<script setup lang="ts">
import { BasicTableProps, useTable } from '/@/hooks/table';
import { getPickApplys,updatePickApply } from '/@/api/platform/wms/pickApply';
import { reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage, TabsPaneContext } from 'element-plus';
import detail from "../pickApply/detail.vue";


// 引入组件
const MenuDialog = defineAsyncComponent(() => import('./form.vue'));

const { t } = useI18n();
const tableRef = ref();
const today = new Date();
const endDate = new Date(today);
endDate.setDate(today.getDate() - 6); // 今天之后的6天，总共一周
today.setDate(today.getDate() + 1);
const createDate = ref([endDate, today]);
const shortcuts = [
	{
		text: 'Last week',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
			return [start, end];
		},
	},
	{
		text: 'Last month',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
			return [start, end];
		},
	},
	{
		text: 'Last 3 months',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
			return [start, end];
		},
	},
];
const getYMD = (date: any) => {
  // 获取年份
  const year = date.getFullYear();

  // 获取月份，注意JavaScript中的月份是从0开始的，因此需要+1
  const month = String(date.getMonth() + 1).padStart(2, '0');

  // 获取日期
  const day = String(date.getDate()).padStart(2, '0');

  // 拼接成 yyyy-MM-dd 格式的字符串
  const formattedDate = `${year}-${month}-${day}`;

  return formattedDate;
};
// 点击行的时候触发
const clickRow = (row: any) => {
    detailsRef.value.query(row);
}
const detailsRef = ref()
// 搜索变量
const queryRef = ref();
//表格的配置
const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {
		PlanDateStart: createDate.value ? getYMD(createDate.value[0]) : '',
    	PlanDateEnd: createDate.value ? getYMD(createDate.value[1]) : ''
	},
	pageList: getPickApplys,
});

const { tableStyle, getDataList, sizeChangeHandle, currentChangeHandle,downBlobFile } = useTable(state);
// 清空搜索条件
const resetQuery = () => {
	// 清空搜索条件
	queryRef.value?.resetFields();
	createDate.value = [endDate, today];
	getDataList(false);
};

const query = () => {
	getDataList();
};
//审核
const audit =async() =>{
	var selectedAry = tableRef.value.getSelectionRows();
	if (selectedAry.length == 0) {
    	ElMessage.error(t('pickApply.selectPickApply'));
    	return;
  	}

	// 提出选择数据中不是已审核的数据，并提示用户去修改
	let arr = selectedAry.filter(item => item.audit_status == "audited" || item.audit_status == "closed");
	if (arr.length > 0) {
		ElMessage.error(t('pickApply.selectedDataContains2') + t('pickApply.onlyNotaudit'));
		return;
	}
	selectedAry.forEach(element => {
		updatePickApply({
			ApplyCode: element.apply_code,
			AuditStatus: "audited"
		}).then((res) => {
       getDataList();
    });
	})


}
//反审核
const notAudit =async() =>{
	var selectedAry = tableRef.value.getSelectionRows();
	if (selectedAry.length == 0) {
    	ElMessage.error(t('pickApply.selectPickApply'));
    	return;
  	}
// 提出选择数据中不是已审核的数据，并提示用户去修改
	let arr = selectedAry.filter(item => item.audit_status == "notAudit" || item.audit_status == "closed");
	if (arr.length > 0 ) {
		ElMessage.error(t('pickApply.selectedDataContains') + t('pickApply.onlyaudit'));
		return;
	}
	// 已审核的数据，可以反审核
	selectedAry.forEach(element => {
    	updatePickApply({
			ApplyCode: element.apply_code,
			AuditStatus: "notAudit"
		}).then((res) => {
      getDataList();
    });
	})


}
//删除
const deletePickApply =() =>{
	var selectedAry = tableRef.value.getSelectionRows();
	if (selectedAry.length == 0) {
    	ElMessage.error(t('pickApply.selectPickApply'));
    	return;
  	}

	selectedAry.forEach(element=>{
		updatePickApply({
			"ApplyCode": element.apply_code,
			"IsDelete": true
    	}).then((res) => {});
	})
	getDataList();
}
//关闭
const closed =() =>{
	var selectedAry = tableRef.value.getSelectionRows();
	if (selectedAry.length == 0) {
    	ElMessage.error(t('pickApply.selectPickApply'));
    	return;
  	}

	selectedAry.forEach(element=>{
		updatePickApply({
			"ApplyCode": element.apply_code,
			"AuditStatus": "closed"
    	}).then((res) => {});
	})
	getDataList();
}
//导出
const exportPickApply =() =>{
	let selectedAry = tableRef.value.getSelectionRows();
  // 未审核的不允许导出
  const hasNotAudited = selectedAry.some(item => item.audit_status === "notAudit");
  if (hasNotAudited) {
    ElMessage.error(t('pickApply.unapprovedDocuments'));
    return;
  }
	if (selectedAry.length != 1) {
    	ElMessage.error(t('pickApply.selectOnePickApply'));
    	return;
  	}
	downBlobFile('/wms/pickApply/ExportPickApplyBarcodes',{"ApplyCode":selectedAry[0].apply_code,"isAll":true},'materialBarcodeReq.xlsx');
}
//导出未完成
const exportNotFinish =() =>{
	var selectedAry = tableRef.value.getSelectionRows();
  // 未审核的不允许导出
  const hasNotAudited = selectedAry.some(item => item.audit_status === "notAudit");
  if (hasNotAudited) {
    ElMessage.error(t('pickApply.unapprovedDocuments'));
    return;
  }
	if (selectedAry.length != 1) {
    	ElMessage.error(t('pickApply.selectOnePickApply'));
    	return;
  	}
	downBlobFile('/wms/pickApply/ExportPickApplyBarcodes',{"ApplyCode":selectedAry[0].apply_code,"isAll":false},'materialBarcodeReq.xlsx');
}
const menuDialogRef = ref();
// 打开新增菜单弹窗
const onOpenAddMenu = (type?: string, row?: any) => {
  menuDialogRef.value.openDialog(type, row);
};
// 根据状态返回对应的 type
const getTagType = (status) => {
  switch (status) {
    case 'create':
      return 'default';
    case 'init':
      return 'info';
    case 'todo':
      return 'warning';
    case 'finish':
      return 'success';
    case 'closed':
      return 'danger';
    default:
      return 'default'; // 默认类型
  }
};
</script>
